---
- name: Create the node_exporter group
  group:
    name: "{{ _node_exporter_system_group }}"
    state: present
    system: true
  when: _node_exporter_system_group != "root"

- name: Create the node_exporter user
  user:
    name: "{{ _node_exporter_system_user }}"
    groups: "{{ _node_exporter_system_group }}"
    append: true
    shell: /usr/sbin/nologin
    system: true
    create_home: false
    home: /
  when: _node_exporter_system_user != "root"

- block:
    - name: Download node_exporter binary to local folder
      become: false
      get_url:
        url: "https://github.com/prometheus/node_exporter/releases/download/v{{ node_exporter_version }}/node_exporter-{{ node_exporter_version }}.linux-{{ go_arch }}.tar.gz"
        dest: "/tmp/node_exporter-{{ node_exporter_version }}.linux-{{ go_arch }}.tar.gz"
        checksum: "sha256:{{ node_exporter_checksum }}"
        mode: '0644'
      register: _download_binary
      until: _download_binary is succeeded
      retries: 5
      delay: 2
      delegate_to: localhost
      check_mode: false

    - name: Unpack node_exporter binary
      become: false
      unarchive:
        src: "/tmp/node_exporter-{{ node_exporter_version }}.linux-{{ go_arch }}.tar.gz"
        dest: "/tmp"
        creates: "/tmp/node_exporter-{{ node_exporter_version }}.linux-{{ go_arch }}/node_exporter"
      delegate_to: localhost
      check_mode: false

    - name: Propagate node_exporter binaries
      copy:
        src: "/tmp/node_exporter-{{ node_exporter_version }}.linux-{{ go_arch }}/node_exporter"
        dest: "{{ _node_exporter_binary_install_dir }}/node_exporter"
        mode: 0755
        owner: root
        group: root
      notify: restart node_exporter
      when: not ansible_check_mode
  when: node_exporter_binary_local_dir | length == 0

- name: propagate locally distributed node_exporter binary
  copy:
    src: "{{ node_exporter_binary_local_dir }}/node_exporter"
    dest: "{{ _node_exporter_binary_install_dir }}/node_exporter"
    mode: 0755
    owner: root
    group: root
  when: node_exporter_binary_local_dir | length > 0
  notify: restart node_exporter